<?php

class session
{
	function __construct()
	{
		if (session_id())
		{
			session_unset();
			session_destroy();
		}
		ini_set('session.save_handler', 'files');
		ini_set('session.use_trans_sid', '0');

		session_cache_limiter('none');
		session_start();
		header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
	}

	function __destruct()
	{
		session_write_close();
	}

	// 获取 session id
	public function get_id()
	{
		return session_id();
	}

	// 获取 session name
	public function get_name()
	{
		return session_name();
	}

	// 获取
	public function get($name, $default = null)
	{
		if (isset($_SESSION[$name]))
		{
			return $_SESSION[$name];
		}
		return $default;
	}

	// 赋值
	public function set($name, $value = null)
	{
		$old_value = isset($_SESSION[$name]) ? $_SESSION[$name] : null;
		if (null === $value) {
			unset($_SESSION[$name]);
		} else {
			$_SESSION[$name] = $value;
		}
		return $old_value;
	}

	// 是否已设置指定名称的 session
	public function has($name)
	{
		return isset($_SESSION[$name]);
	}

	// 清除指定名称的 session
	public function clear($name)
	{
		$value = null;
		if (isset($_SESSION[$name])) {
			$value = $_SESSION[$name];
			unset($_SESSION[$name]);
		}
		return $value;
	}

	// 销毁 session
	public function destroy()
	{
		if (isset($_COOKIE[session_name()])) {
			setcookie(session_name(), '', time()-42000, '', '/');
		}
		session_unset();
		session_destroy();
		return true;
	}

	public function restart()
	{
		$this->destroy();
		$id	= $this->create_id();
		session_id($id);

		$this->_start();
		return true;
	}


	private function create_id()
	{
		$id = 0;
		while (strlen($id) < 32)  {
			$id .= mt_rand(0, mt_getrandmax());
		}

		$id	= md5(uniqid($id, true));
		return $id;
	}

}